# -*- encoding: utf-8 -*-
# @File    : server.py
# @Date    : 2020/12/25
# @Author  : 韩林新

import socket
import os
import time
import pyautogui

from .config import server_address
from .config import BUFFSIZE
from .config import debug
from .config import wait_time

from .ProcessData import getlines
from .ProcessData import resolve

from .ControlList import ControlList
from .Path import PathData


def get_ctrls(con, ret):
    """
    从con数据中获取控件信息

    Parameters
        con  socket连接
        ret  获取到的控件信息

    Returns
        True  成功
        False  失败
    """
    rin = ""
    if debug:
        print("send a request")
    try:
        con.sendall("send".encode(encoding='utf-8'))
    except:
        return False
    try:
        while True:
            # if debug:
            #     print("before get data")
            data = con.recv(BUFFSIZE)
            # if debug:
            #     print("have get data")

            if data:
                data = data.decode(encoding='utf-8')
                lines, rin = getlines(rin+data)
                end = resolve(lines, ret)
                if end:
                    break
            else:
                raise ValueError("client broken socket!")
    except:
        return False
    return True



def server():
    """
    和WineServer交互信息
    """

    try:
        os.unlink(server_address)
    except OSError:
        if os.path.exists(server_address):
            raise
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.bind(server_address)
    sock.listen(1)

    while True:
        print("listen")
        connection, _ = sock.accept()
        print("get a connection")
        time.sleep(wait_time)
        update()
        ctrls = ControlList()
        path_data = PathData()
        i = 0
        try:
            while i < path_data.steps:
                time.sleep(wait_time)
                if not get_ctrls(connection, ctrls):
                    raise ValueError("get ctrls failed!")
                path_data.check(ctrls)
                i += 1
                # s = input("input a string,enter to quit")
                # if not s:
                #     break
            path_data.get_results()
        finally:
            connection.close()


def update():
    pyautogui.hotkey('winleft','d')
    pyautogui.hotkey('winleft','d')
